import { lazy } from 'react'
import {
  createBrowserRouter,
  createHashRouter,
  Navigate,
  RouteObject,
  RouterProvider,
} from 'react-router-dom'
import { SidebarLayout } from '@/layout'
import { AuthInterceptor } from './components'
import { StaticRoutes } from './impl/StaticRoute'

interface RouterProps {
  /** 路由模式，默认为浏览器路由 */
  mode?: 'HashRouter' | 'BrowserRouter'
}

/**
 * 登录路由
 */
const LoginRoute: RouteObject = {
  path: '/login',
  Component: lazy(() => import('@/page/login')),
}

/**
 *  404路由
 * - 当路由均无匹配时，匹配此路由跳转到404界面
 */
const PAGE_NOT_FOUND_ROUTE: RouteObject = {
  path: '*',
  element: <Navigate to="/404" replace />,
}

/**
 * 路由定义
 */
export default function Router(props: RouterProps) {
  const { mode = 'BrowserRouter' } = props
  // 异步路由
  const asyncRoutes: RouteObject = {
    path: '/',
    element: (
      <AuthInterceptor>
        <SidebarLayout />
      </AuthInterceptor>
    ),
    children: [...StaticRoutes],
  }
  const routes = [LoginRoute, asyncRoutes, PAGE_NOT_FOUND_ROUTE]
  const router = createRoute(mode, routes)
  return <RouterProvider router={router} />
}

/**
 * 根据路由模式创建路由
 * @param mode 路由模式
 * @param routes 路由定义
 */
function createRoute(mode: RouterProps['mode'], routes: RouteObject[]) {
  if (mode === 'HashRouter') return createHashRouter(routes)
  return createBrowserRouter(routes)
}
